package scheduler

import (
	"os"
	"path/filepath"
	"runtime/debug"
	"time"

	"github.com/sirupsen/logrus"
)

func DirDelScheduler(dirPath string) {
	defer func() {
		if info := recover(); info != nil {
			logrus.Error("删除目录出现严重异常：", info, string(debug.Stack()))
		}
	}()
	var dirPaths []string
	dirErr := filepath.Walk(dirPath, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			dirPaths = append(dirPaths, path)
			return nil
		}
		return nil
	})
	if dirErr != nil {
		logrus.Error("读取目录信息错误：", dirErr.Error())
		return
	}

	diff, _ := time.ParseDuration("-48h")
	for i := range dirPaths {
		f, err := os.Stat(dirPaths[i])
		if err != nil {
			continue
		} else {
			dirModiTime := f.ModTime()
			if dirModiTime.Before(time.Now().Add(diff)) {
				os.RemoveAll(dirPaths[i])
			}
		}
	}
}
